﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;

namespace Fast
{
    /// <summary>
    /// 运行应用程序启动类
    /// </summary>
    public class StartupManager : IStartupManager
    {
        private readonly FastStartupOptions _options;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="options"></param>
        internal StartupManager(FastStartupOptions options)
        {
            _options = options;
        }

        /// <summary>
        /// 配置服务
        /// </summary>
        /// <param name="context"></param>
        public void ConfigureServices(ConfigureServicesContext context)
        {
            foreach (var item in _options.FastStartups.OrderByDescending(s => GetOrder(s.GetType())))
            {
                item.ConfigureServices(context);
            }
        }

        /// <summary>
        /// 配置管道
        /// </summary>
        /// <param name="context"></param>
        public void Configure(ConfigureContext context)
        {
            foreach (var item in _options.FastStartups.OrderByDescending(s => GetOrder(s.GetType())))
            {
                item.Configure(context);
            }
        }

        /// <summary>
        /// 获取 Startup 排序
        /// </summary>
        /// <param name="type">排序类型</param>
        /// <returns>int</returns>
        private int GetOrder(Type type)
        {
            return !type.IsDefined(typeof(FastStartupAttribute), true)
                ? 0
                : type.GetCustomAttribute<FastStartupAttribute>(true).Order;
        }
    }
}
